package com.itheima.web;

import com.itheima.dao.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    UserService service = new UserServiceImpl();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        String remember = request.getParameter("remember");

        User user = service.select(username, password);
        System.out.println(user);

        if (user != null) {

            if ("1".equals(remember)) {
                Cookie c_username = new Cookie("username", username);
                Cookie c_password = new Cookie("password", password);

                c_username.setMaxAge(60 * 60 * 24 * 7);
                c_password.setMaxAge(60 * 60 * 24 * 7);

                response.addCookie(c_username);
                response.addCookie(c_password);
            }
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            System.out.println(user);

            response.setContentType("text/html;charset=utf-8");

            String contextPath = request.getContextPath();
            //System.out.println(contextPath);
            if ("admin".equals(username)) {
                request.getRequestDispatcher("/book.jsp").forward(request, response);
               // request.getRequestDispatcher("/a.jsp").forward(request, response);
                //response.sendRedirect(contextPath+"/a.jsp");
            } else if (!("admin".equals(username))) {
                request.getRequestDispatcher("/borrowBook.jsp").forward(request, response);
            }

        }else {
            request.setAttribute("login_msg", "用户名或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }


}
